package com.peanut.baby.mvp.liveroom;

import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.model.LiveMsg;
import com.peanut.baby.util.ImageUtil;
import com.peanut.baby.util.TimeUtil;
import com.peanut.baby.widget.im.MsgThumbImageView;
import com.peanut.devlibrary.adapter.AppRecycleViewHolder;
import com.peanut.devlibrary.adapter.AppRecyclerAdapter;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.picker.PhotoPreviewActivity;
import com.peanut.devlibrary.util.FileUtil;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import static com.peanut.baby.R.id.timestamp;

/**
 * Created by anonymouslystudio on 2017/7/19.
 */

public class LiveRoomMessageAdapter extends AppRecyclerAdapter<LiveMsg> {
    private static final String TAG = LiveRoomMessageAdapter.class.getSimpleName();

    private static final int MAX_AUDIO_TIME_SECOND = 60;

    private static final int VIEW_TYPE_UNSUPPORTED          = 0;
    private static final int VIEW_TYPE_TEXT_RECEIVE         = 1;
    private static final int VIEW_TYPE_IMAGE_RECEIVE        = 2;
    private static final int VIEW_TYPE_VOICE_RECEIVE        = 3;
    private static final int VIEW_TYPE_TEXT_SEND            = 4;
    private static final int VIEW_TYPE_IMAGE_SEND           = 5;
    private static final int VIEW_TYPE_VOICE_SEND           = 6;

    private  OnAudioPlayFinishedListener    listener;

    public void setOnAudioPlayFinishedListener(OnAudioPlayFinishedListener lis){
        listener = lis;
    }

    public LiveRoomMessageAdapter(List<LiveMsg> dataList) {
        super(dataList);
    }

    @Override
    public int getLayoutId(int viewType) {

        int resId = R.layout.ease_row_received_unsupported;
        switch (viewType){
            case VIEW_TYPE_IMAGE_RECEIVE:
                resId = R.layout.ease_row_received_picture;
                break;
            case VIEW_TYPE_TEXT_RECEIVE:
                resId = R.layout.ease_row_received_message;
                break;
            case VIEW_TYPE_VOICE_RECEIVE:
                resId = R.layout.ease_row_received_voice;
                break;
            case VIEW_TYPE_IMAGE_SEND:
                resId = R.layout.ease_row_sent_picture;
                break;
            case VIEW_TYPE_TEXT_SEND:
                resId = R.layout.ease_row_sent_message;
                break;
            case VIEW_TYPE_VOICE_SEND:
                resId = R.layout.ease_row_sent_voice;
                break;

        }
        return resId;
    }

    @Override
    public void convert(AppRecycleViewHolder holder, LiveMsg message, int position) {
        bindViewAndSpiltDiff(holder,message,position);
    }



    @Override
    public int getItemViewType(int position) {
        int viewType = VIEW_TYPE_UNSUPPORTED;
        LiveMsg message = getItem(position);
        if(InitManager.getInstance().getUser().userId.equals(message.creatorId+"")){
            //send
            if(message.messageType == LiveMsg.TYPE_TEXT){
                viewType = VIEW_TYPE_TEXT_SEND;
            }else if(message.messageType == LiveMsg.TYPE_IMAGE){
                viewType = VIEW_TYPE_IMAGE_SEND;
            }else if(message.messageType == LiveMsg.TYPE_VOICE){
                viewType = VIEW_TYPE_VOICE_SEND;
            }
        }else{
            if(message.messageType == LiveMsg.TYPE_TEXT){
                viewType = VIEW_TYPE_TEXT_RECEIVE;
            }else if(message.messageType == LiveMsg.TYPE_IMAGE){
                viewType = VIEW_TYPE_IMAGE_RECEIVE;
            }else if(message.messageType == LiveMsg.TYPE_VOICE){
                viewType = VIEW_TYPE_VOICE_RECEIVE;
            }
        }

        return viewType;
    }

    private void bindViewAndSpiltDiff(AppRecycleViewHolder holder, LiveMsg o, int position){
        ImageView avatar = (ImageView) holder.getView(R.id.iv_userhead);
        TextView  timeStamp = (TextView) holder.getView(timestamp);
        TextView  nick = (TextView) holder.getView(R.id.tv_userid);

        if(o.nickname.equals("客服")){
            avatar.setImageResource(R.mipmap.ic_launcher);
        }else{
            ImageLoader.getInstance().loadImageView(avatar.getContext(),o.avatar,avatar);
        }

        if(nick != null){
            nick.setText(o.nickname);
        }

        if (position == 0) {
            timeStamp.setText(TimeUtil.getDisplayTimeMillis(o.createTime));
            timeStamp.setVisibility(View.VISIBLE);
        } else {
            // show time stamp if interval with last message is > 30 seconds
            LiveMsg prevMessage = getItem(position - 1);
            if (prevMessage != null && TimeUtil.isCloseEnough(o.createTime, prevMessage.createTime)) {
                timeStamp.setVisibility(View.GONE);
            } else {
                timeStamp.setText(TimeUtil.getDisplayTimeMillis(o.createTime));
                timeStamp.setVisibility(View.VISIBLE);
            }
        }

        int type = o.messageType;

        if(type == LiveMsg.TYPE_TEXT){
            convertTextLayout(holder,o,position);
        }else if(type == LiveMsg.TYPE_IMAGE){
            convertImageLayout(holder,o,position);
        }else if(type == LiveMsg.TYPE_VOICE){
            convertVoiceLaypout(holder,o,position);
        }else{
            convertUnSupportedLaypout(holder,o,position);
        }
    }


    private void convertTextLayout(AppRecycleViewHolder holder, LiveMsg o, int position){

        TextView  content = (TextView) holder.getView(R.id.tv_chatcontent);
        content.setText(o.getMessageContent().text);
        holder.getView(R.id.bubble).setOnClickListener(null);
    }
    private void convertImageLayout(AppRecycleViewHolder holder, final LiveMsg o, int position){
        final MsgThumbImageView imageView = (MsgThumbImageView) holder.getView(R.id.image);
        setImageSize(o.getMessageContent().width,o.getMessageContent().height,imageView);

        Glide.with(imageView.getContext())
                .load(o.getMessageContent().url)
                .asBitmap()
                .toBytes()
                .into(new SimpleTarget<byte[]>(250, 250) {
                    @Override
                    public void onResourceReady(byte[] data, GlideAnimation anim) {
                        String path = InitManager.getInstance().getCacheImagePath(getFileNameFromUrl(o.getMessageContent().url));
                        try {
                            FileUtil.savaFileToSD(path,data);
                            imageView.loadAsPath(path,o.getMessageContent().width,o.getMessageContent().height,R.drawable.ease_chat_mask_bg);
                        } catch (Exception e) {
                            imageView.loadAsResource(R.drawable.icon_default_logo,R.drawable.ease_chat_mask_bg);
                        }

                    }
                });
        holder.getView(R.id.bubble).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> urls = new ArrayList<String>();
                urls.add(o.getMessageContent().url);
                PhotoPreviewActivity.start(imageView.getContext(),urls,0);
            }
        });

    }
    private void convertVoiceLaypout(final AppRecycleViewHolder holder, final LiveMsg o, final int position){
        ImageView voiceImageView = ((ImageView) holder.getView(R.id.play_icon));
        TextView voiceLengthView = (TextView) holder.getView(R.id.tv_length);
        RelativeLayout bubble = (RelativeLayout) holder.getView(R.id.bubble);

        int len = o.getMessageContent().duration;
        setAudioBubbleWidth(bubble,len);

        if(len>0){
            voiceLengthView.setText(len + "\"");
            voiceLengthView.setVisibility(View.VISIBLE);
        }else{
            voiceLengthView.setVisibility(View.INVISIBLE);
        }


        if (AppVoicePlayer.getInstance().isPlaying()
                && AppVoicePlayer.getInstance().getUrl().equals(o.getMessageContent().url) ) {
            AnimationDrawable voiceAnimation;
            if (!InitManager.getInstance().getUserId().equals(o.creatorId+"")) {
                voiceImageView.setImageResource(R.drawable.voice_from_icon);
            } else {
                voiceImageView.setImageResource(R.drawable.voice_to_icon);
            }
            voiceAnimation = (AnimationDrawable) voiceImageView.getDrawable();
            voiceAnimation.start();
        } else {
            if (!InitManager.getInstance().getUserId().equals(o.creatorId+"")) {
                voiceImageView.setImageResource(R.drawable.ease_chatfrom_voice_playing_f3);
            } else {
                voiceImageView.setImageResource(R.drawable.ease_chatto_voice_playing_f3);
            }
        }

        holder.getView(R.id.bubble).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                String currentUrl = AppVoicePlayer.getInstance().getUrl();
                Log.d("RoomLectureFragment","isPlaying3? "+AppVoicePlayer.getInstance().isPlaying()+"" +
                        "\n\t currentPlayUrl: "+currentUrl+"" +
                        "\n\t msgUrl "+o.getMessageContent().url);
                if(AppVoicePlayer.getInstance().isPlaying() && currentUrl.equals(o.getMessageContent().url)){
                    Log.d(RoomLectureFragment.class.getSimpleName(),"same child click");
                    AppVoicePlayer.getInstance().releasePlayer();
                }else{
                    AppVoicePlayer.getInstance().play(o.getMessageContent().url,
                            InitManager.getInstance().getUserId().equals(o.creatorId+""),
                            v, new AppVoicePlayer.OnAppVoicePlayListener() {
                                @Override
                                public void onException(String reason) {
                                    Toast.makeText(v.getContext(),"音频播放出错",Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onPlayFinished() {
                                    if(listener != null){
                                        listener.onAudioPlayFinished(position);
                                    }
                                }

                                @Override
                                public void onPlayStarted() {

                                }

                                @Override
                                public void onInterrupt() {

                                }

                            });
                }

            }
        });


    }

    private void convertUnSupportedLaypout(AppRecycleViewHolder holder, LiveMsg o, int position){
        TextView  content = (TextView) holder.getView(R.id.tv_chatcontent);
        content.setText("当前版本不支持此消息类型，请升级新版后查看");
        holder.getView(R.id.bubble).setOnClickListener(null);
    }


    //some common method
    public static int getAudioMaxEdge() {
        return (int) (0.6 * InitManager.getInstance().getScreenWidth());
    }

    public static int getAudioMinEdge() {
        return (int) (0.1875 * InitManager.getInstance().getScreenWidth());
    }

    public static void setAudioBubbleWidth(View bubbleLayout, int seconds) {
        int currentBubbleWidth = calculateBubbleWidth(seconds, MAX_AUDIO_TIME_SECOND);
        Log.d(TAG,"currentBubbleWidth: "+currentBubbleWidth);
        ViewGroup.LayoutParams layoutParams = bubbleLayout.getLayoutParams();
        layoutParams.width = currentBubbleWidth;
        bubbleLayout.setLayoutParams(layoutParams);
    }



    public static int calculateBubbleWidth(long seconds, int MAX_TIME) {
        int maxAudioBubbleWidth = getAudioMaxEdge();
        int minAudioBubbleWidth = getAudioMinEdge();

        int currentBubbleWidth;
        if (seconds <= 0) {
            currentBubbleWidth = minAudioBubbleWidth;
        } else if (seconds > 0 && seconds <= MAX_TIME) {
            currentBubbleWidth = (int) ((maxAudioBubbleWidth - minAudioBubbleWidth) * (2.0 / Math.PI)
                    * Math.atan(seconds / 10.0) + minAudioBubbleWidth);
        } else {
            currentBubbleWidth = maxAudioBubbleWidth;
        }

        if (currentBubbleWidth < minAudioBubbleWidth) {
            currentBubbleWidth = minAudioBubbleWidth;
        } else if (currentBubbleWidth > maxAudioBubbleWidth) {
            currentBubbleWidth = maxAudioBubbleWidth;
        }

        return currentBubbleWidth;
    }

    //image message related
    private void setImageSize(String thumbPath) {
//        int[] bounds = null;
//        if (thumbPath != null) {
//            bounds = BitmapDecoder.decodeBound(new File(thumbPath));
//        }
//        if (bounds == null) {
//            if (message.getType() == EMMessage.Type.IMAGE) {
//                EMImageMessageBody body = (EMImageMessageBody) message.getBody();
//                bounds = new int[]{body.getWidth(), body.getHeight()};
//            }
//        }
//
//        if (bounds != null) {
//            ImageUtil.ImageSize imageSize = ImageUtil.getThumbnailDisplaySize(bounds[0], bounds[1], getImageMaxEdge(), getImageMinEdge());
//            setLayoutParams(imageSize.width, imageSize.height, imageView);
//        }
    }

    private void setImageSize(int width,int height,ImageView imageView) {
//        int[] bounds = null;
//        if (thumbPath != null) {
//            bounds = BitmapDecoder.decodeBound(new File(thumbPath));
//        }
//        if (bounds == null) {
//            if (message.getType() == EMMessage.Type.IMAGE) {
//                EMImageMessageBody body = (EMImageMessageBody) message.getBody();
//                bounds = new int[]{body.getWidth(), body.getHeight()};
//            }
//        }
//
//        if (bounds != null) {
//            ImageUtil.ImageSize imageSize = ImageUtil.getThumbnailDisplaySize(bounds[0], bounds[1], getImageMaxEdge(), getImageMinEdge());
//            setLayoutParams(imageSize.width, imageSize.height, imageView);
//        }

        ImageUtil.ImageSize imageSize = ImageUtil.getThumbnailDisplaySize(width, height, getImageMaxEdge(), getImageMinEdge());
            setLayoutParams(imageSize.width, imageSize.height, imageView);
    }

    public static int getImageMaxEdge() {
        return (int) (165.0 / 320.0 * InitManager.getInstance().getScreenWidth());
    }

    public static int getImageMinEdge() {
        return (int) (76.0 / 320.0 * InitManager.getInstance().getScreenWidth());
    }

    protected void setLayoutParams(int width, int height, View... views) {
        for (View view : views) {
            ViewGroup.LayoutParams maskParams = view.getLayoutParams();
            maskParams.width = width;
            maskParams.height = height;
            view.setLayoutParams(maskParams);
        }
    }


    private String getFileNameFromUrl(String url){
        String[] spilt = url.split("/");
        return spilt[spilt.length - 1];
    }

    public interface OnAudioPlayFinishedListener{
        void onAudioPlayFinished(int position);
    }
}
